package io.ai.arch.java.mq.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


//@Configuration
public class RabbitPolicyConfig {

    private final RestTemplate restTemplate = new RestTemplate();
    ;
    @Value("${spring.rabbitmq.username}")
    private String adminUsername;
    @Value("${spring.rabbitmq.password}")
    private String adminPassword;
    @Value("${spring.rabbitmq.addresses}")
    private String rabbitHost;
    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;

    @Value("${spring.application.name}")
    private String appName;

    // 声明目标队列（策略将应用在这些队列上）
    @Bean
    public Queue orderProcessingQueue() {
        return new Queue("orders.processing", true);
    }

    @Bean
    public Queue paymentQueue() {
        return new Queue("payments.queue", true);
    }

    // 策略配置执行器
    @Bean
    public CommandLineRunner policyInitializer() {
        return args -> {
            applyPolicy(appName.replace(".", "-") + "-dl-policy");
        };
    }

    // 策略应用核心方法
    private void applyPolicy(String policyName) {
        String host = rabbitHost.split(",")[0];
        String url = String.format("http://%s:15672/api/policies/%s/%s", host, URLEncoder.encode(virtualHost, StandardCharsets.UTF_8), policyName);

        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(adminUsername, adminPassword);
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 策略定义 - 以订单死信策略为例
        String policyDefinition = """
                {
                    "pattern": "^%s$",
                    "definition": {
                        "dead-letter-exchange": "%s",
                        "dead-letter-routing-key": "%s"
                    }
                }
                """.formatted(("queue-" + appName).replace(".", "-") + ".*", RabbitMQConfig.exchangeName, RabbitMQConfig.routingKey);

        HttpEntity<String> request = new HttpEntity<>(policyDefinition, headers);

        try {
            restTemplate.exchange(url, HttpMethod.PUT, request, String.class);
            System.out.println("策略应用成功: " + policyName);
        } catch (HttpClientErrorException.Conflict e) {
            System.out.println("策略已存在: " + policyName);
        } catch (Exception e) {
            System.err.println("策略配置失败: " + e.getMessage());
        }
    }

    // 死信交换机和队列声明
    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange("dlx.exchange");
    }

    @Bean
    public Queue deadLetterQueue() {
        return new Queue("dead.letters");
    }

    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with("dead.#");
    }
}